package org.framework.lazy.cloud.network.heartbeat.client.netty.proxy.socks.socket;


import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.socksx.v5.Socks5AddressType;
import lombok.extern.slf4j.Slf4j;
import org.framework.lazy.cloud.network.heartbeat.client.config.NettyClientProperties;
import org.framework.lazy.cloud.network.heartbeat.client.netty.proxy.socks.NettySocksClientProxyClient;
import org.framework.lazy.cloud.network.heartbeat.client.netty.proxy.socks.filter.NettySocksClientProxyClientVisitorTransferFilter;
import org.framework.lazy.cloud.network.heartbeat.client.netty.proxy.socks.filter.NettySocksClientProxyServerTransferFilter;
import org.framework.lazy.cloud.network.heartbeat.common.adapter.ChannelTypeAdapter;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.payload.NettyProxyMsg;
import org.framework.lazy.cloud.network.heartbeat.common.constant.ProxyMessageType;
import org.framework.lazy.cloud.network.heartbeat.common.factory.EventLoopGroupFactory;
import org.framework.lazy.cloud.network.heartbeat.common.utils.ChannelAttributeKeyUtils;

import java.util.concurrent.TimeUnit;


@Slf4j
public class NettySocksClientProxyClientVisitorTransferSocket {

    /**
     * 连接服务端通信通道
     */
    public static void buildTransferServer(NettySocksClientProxyClient nettySocksClientProxyClient, Channel visitorChannel) {

        EventLoopGroup eventLoopGroup = EventLoopGroupFactory.createClientWorkGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(eventLoopGroup)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.SO_KEEPALIVE, true)
                // 设置读缓冲区为2M
                .option(ChannelOption.SO_RCVBUF, 2048 * 1024)
                // 设置写缓冲区为1M
                .option(ChannelOption.SO_SNDBUF, 1024 * 1024)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000 * 60)//连接超时时间设置为 60 秒
                .option(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(1024 * 1024, 1024 * 1024 * 2))
                .handler(new NettySocksClientProxyClientVisitorTransferFilter(new ChannelTypeAdapter(nettySocksClientProxyClient.getHandleChannelTypeAdvancedList())))
        ;
        NettyClientProperties nettyClientProperties = nettySocksClientProxyClient.getNettyClientProperties();
        String inetHost = nettyClientProperties.getInetHost();
        int inetPort = nettyClientProperties.getInetPort();
        // local client id
        String clientId = nettyClientProperties.getClientId();

        String targetIp = nettySocksClientProxyClient.getTargetIp();
        Integer targetPort = nettySocksClientProxyClient.getTargetPort();
        String targetClientId = nettySocksClientProxyClient.getTargetClientId();

        Socks5AddressType socks5AddressType = nettySocksClientProxyClient.getSocks5AddressType();
        byte socks5AddressTypeByteValue = socks5AddressType.byteValue();

        String visitorId = ChannelAttributeKeyUtils.getVisitorId(visitorChannel);



        // 客户端链接服务端
        log.info("Client creates a new proxy channel to connect to server IP: {}, connecting to server port: {} with clientId:【{}】 & visitorId:【{}】",
                inetHost, inetPort, clientId, visitorId);
        ChannelFuture future = bootstrap.connect(inetHost, inetPort);

        // 使用的客户端ID:{}
        future.addListener((ChannelFutureListener) futureListener -> {
            Channel transferChannel = futureListener.channel();
            if (futureListener.isSuccess()) {

                NettyProxyMsg nettyProxyMsg = new NettyProxyMsg();
                nettyProxyMsg.setType(ProxyMessageType.SOCKS_REPORT_CLIENT_PROXY_CLIENT_TRANSFER_CONNECTION_);
                // other clientId
                nettyProxyMsg.setClientTargetIp(targetIp);
                nettyProxyMsg.setClientTargetPort(targetPort);
                nettyProxyMsg.setClientId(targetClientId);
                nettyProxyMsg.setVisitorId(visitorId);
                nettyProxyMsg.setData(new byte[]{socks5AddressTypeByteValue});
                transferChannel.writeAndFlush(nettyProxyMsg);
                // 绑定客户端真实通信通道
                ChannelAttributeKeyUtils.buildVisitorId(transferChannel, visitorId);
                ChannelAttributeKeyUtils.buildClientId(transferChannel, clientId);
                // 传输通道
                ChannelAttributeKeyUtils.buildNextChannel(visitorChannel, transferChannel);
                ChannelAttributeKeyUtils.buildNextChannel(transferChannel, visitorChannel);


            } else {
                log.info("无法连接到服务端....");
                eventLoopGroup.schedule(() -> {
                    try {
                        buildTransferServer(nettySocksClientProxyClient, visitorChannel);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }, 2, TimeUnit.SECONDS);
            }
        });
    }
}